package com.hbx.gift.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hbx.gift.client.loginUserFeignClient;
import com.hbx.gift.domain.Employee;
import com.hbx.gift.domain.LoginUser;
import com.hbx.gift.domain.Tenant;
import com.hbx.gift.domain.TenantMeal;
import com.hbx.gift.enums.SystemErrorCode;
import com.hbx.gift.exception.BusinessException;
import com.hbx.gift.mapper.TenantMapper;
import com.hbx.gift.service.IEmployeeService;
import com.hbx.gift.service.ITenantMealService;
import com.hbx.gift.service.ITenantService;
import com.hbx.gift.util.AjaxResult;
import com.hbx.gift.util.RonghuaAssert;
import com.hbx.gift.util.encrypt.MD5;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbx
 * @since 2024-07-19
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private ITenantMealService tenantMealService;

    @Autowired
    private loginUserFeignClient loginUserFeignClient;

    @Autowired
    private IEmployeeService employeeService;


    @Override
//    @Transactional
    @GlobalTransactional(rollbackFor = Exception.class) //分布式事务
    public void settlement(Tenant tenant) {

        //生成数据前检查工作
        checkData(tenant);

        Employee admin = tenant.getAdmin();
        //admin.setLoginId();
        admin.setPassword(MD5.getMD5(admin.getPassword()));
        admin.setInputTime(new Date());
        admin.setState(1);//1 正常

        //组装登录信息对象-->远程调用
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(admin.getUsername());
        loginUser.setPassword(admin.getPassword());
        loginUser.setEmail(admin.getEmail());
        loginUser.setTel(admin.getTel());
        loginUser.setType(LoginUser.USER_ADMIN);
        AjaxResult ajaxResult = loginUserFeignClient.addOrUpdate(loginUser);
        //生成employee数据
        //解析调用的结果

        RonghuaAssert.isTrue(ajaxResult.getSuccess(),SystemErrorCode.RESPONSE_CODE_40001);
        //获取远程数据
        String jsonString = JSON.toJSONString(ajaxResult.getData());
        LoginUser user = JSONObject.parseObject(jsonString, LoginUser.class);
        Long loginId = user.getId();
        admin.setLoginId(loginId);
        employeeService.insert(admin);
        //生成租户信息
        tenant.setRegisterTime(new Date());
        tenant.setState(0);//待审核
        tenant.setAdminId(admin.getId());
        super.insert(tenant);
        //生成中间表
        TenantMeal meal = new TenantMeal();
        meal.setMealId(tenant.getMealId());
        meal.setTenantId(tenant.getId());
//        System.out.println(1/0);
        tenantMealService.insert(meal);

    }

    private void checkData(Tenant tenant) {
        EntityWrapper<Tenant> wrapper = new EntityWrapper<>();
        wrapper.eq("company_name",tenant.getCompanyName());
        // 店铺名查重
        Integer count = tenantMapper.selectCount(wrapper);
        if (count!=0){
            throw  new BusinessException(SystemErrorCode.RESPONSE_CODE_400002);
        }
        // 管理员用户名查重
        EntityWrapper<Employee> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("username",tenant.getAdmin().getUsername());
        Employee employee = employeeService.selectOne(entityWrapper);

        RonghuaAssert.isNull(employee,SystemErrorCode.RESPONSE_CODE_500007);
        //4.两次密码输入是否一致
        RonghuaAssert.isEq(tenant.getAdmin().getPassword(),
                tenant.getAdmin().getConfirmPassword(),
                SystemErrorCode.RESPONSE_CODE_400001);

    }

}
